package user

import (
	"clouds.lgb24kcs.cn/controllers/user/request"
	"clouds.lgb24kcs.cn/errorx"
	"clouds.lgb24kcs.cn/global"
	"clouds.lgb24kcs.cn/models"
	"clouds.lgb24kcs.cn/utils"
	"github.com/gin-gonic/gin"
	"os"
	"time"
)

type UserUpdataAPI struct {
}

var DIR, _ = os.Getwd()
var Updata UserUpdataAPI

func (u *UserUpdataAPI) UserUpdata(c *gin.Context, req request.UpdataReq, id int64) {
	// TODO 处理用户不上传头像数据，导致报错问题
	file, err := c.FormFile("head")
	var HeadImg string
	if err != nil {
		utils.Fail(c, errorx.UserUpload, "请上传头像")
	} else {
		utils.PathExists(DIR + global.APP.Configuration.Server.Upload + "/" + "headImg")
		if err := c.SaveUploadedFile(file, DIR+global.APP.Configuration.Server.Upload+"/"+"headImg/"+file.Filename); err != nil {
			global.APP.Log.Error(err.Error())
			utils.Fail(c, errorx.UserUpload, "用户头像更新失败")
		} else {
			HeadImg = "http://" + global.APP.Configuration.Server.LOCAL + ":" + global.APP.Configuration.Server.Port + "/static/headImg/" + file.Filename
			userinfo := models.User{}
			tx := global.APP.DB.Model(&userinfo).Where("id=?", id).Updates(models.User{
				Username:  req.Username,
				HeaderImg: HeadImg,
			})
			if tx.Error != nil {
				global.APP.Log.Error(tx.Error.Error())
				utils.Fail(c, errorx.UserUpload, "用户更新失败")
			} else if tx.RowsAffected == 0 {
				utils.Fail(c, errorx.UserUpload, "用户信息不存在")

			} else {
				utils.Success(c, 0, request.UpdataResp{
					ID:       int64(userinfo.ID),
					Username: userinfo.Username,
					Mobile:   userinfo.Mobile,
					HeadImg:  userinfo.HeaderImg,
					CreateAt: userinfo.CreatedAt.Format(time.DateTime),
					UpdateAt: userinfo.UpdatedAt.Format(time.DateTime),
				})
			}
		}
	}
}
